<template>
  <div class="role-management">
    <!-- 固定头部区域 -->
    <div class="page-header-fixed">
      <div class="page-title">
        <h2>角色权限管理</h2>
        <div class="action-bar">
          <a-button
            type="primary"
            @click="handleCreate"
            v-permission="'k7w2f6b4'"
          >
            <template #icon><PlusOutlined /></template>
            新增角色
          </a-button>
        </div>
      </div>
    </div>

    <!-- 可滚动内容区 -->
    <div class="page-content">
      <div class="content-container">
        <!-- 左侧：角色列表 -->
        <div class="role-list">
          <div class="list-header">
            <h3>角色列表</h3>
          </div>

          <a-card class="table-card">
            <a-table
              :columns="columns"
              :data-source="roleList"
              :loading="loading"
              :pagination="false"
              :scroll="{ y: 'calc(100vh - 480px)' }"
              :row-class-name="getRowClassName"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="record.status === 1 ? 'green' : 'red'">
                    {{ record.status === 1 ? "启用" : "禁用" }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'isSystem'">
                  <a-tag v-if="record.isSystem === 1" color="purple">
                    {{ getRoleTypeName(record.roleCode) }}
                  </a-tag>
                  <a-tag v-else color="default">自定义</a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <!-- 系统角色但当前用户权限不足时显示提示 -->
                  <template
                    v-if="
                      record.isSystem === 1 && !canManageRole(record.roleCode)
                    "
                  >
                    <div class="admin-tip">
                      <small style="color: var(--text-secondary)">
                        {{ getRoleTypeName(record.roleCode) }}，权限不足无法编辑
                      </small>
                    </div>
                  </template>
                  <!-- SUPER_ADMIN角色：只允许分配权限，不允许编辑和删除 -->
                  <template
                    v-else-if="
                      record.isSystem === 1 &&
                      record.roleCode === 'SUPER_ADMIN' &&
                      canManageRole(record.roleCode)
                    "
                  >
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click="handleAssignPermissions(record)"
                        v-permission="'y4n8g2z9'"
                      >
                        分配权限
                      </a-button>
                      <a-tooltip title="超级管理员角色不可编辑基础信息">
                        <a-button type="link" size="small" disabled>
                          编辑
                        </a-button>
                      </a-tooltip>
                      <a-tooltip title="超级管理员角色不可删除">
                        <a-button type="link" size="small" disabled danger>
                          删除
                        </a-button>
                      </a-tooltip>
                    </a-space>
                  </template>
                  <!-- 其他系统角色（如SITE_ADMIN）：允许分配权限，可以编辑但不可删除 -->
                  <template
                    v-else-if="
                      record.isSystem === 1 &&
                      record.roleCode !== 'SUPER_ADMIN' &&
                      canManageRole(record.roleCode)
                    "
                  >
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click="handleAssignPermissions(record)"
                        v-permission="'y4n8g2z9'"
                      >
                        分配权限
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        @click="handleEdit(record)"
                        v-permission="'p1m9x5v8'"
                      >
                        编辑
                      </a-button>
                      <a-tooltip title="系统内置角色不可删除">
                        <a-button type="link" size="small" disabled danger>
                          删除
                        </a-button>
                      </a-tooltip>
                    </a-space>
                  </template>
                  <!-- 自定义角色，显示所有操作 -->
                  <a-space v-else>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleAssignPermissions(record)"
                      v-permission="'y4n8g2z9'"
                    >
                      分配权限
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleEdit(record)"
                      v-permission="'p1m9x5v8'"
                    >
                      编辑
                    </a-button>
                    <a-popconfirm
                      title="确定删除此角色吗？"
                      @confirm="handleDelete(record.id)"
                      v-permission="'q6j3h7c1'"
                    >
                      <a-button type="link" size="small" danger>
                        删除
                      </a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>

          <!-- 分页器 -->
          <div class="pagination-wrapper">
            <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :show-total="(total: number) => `共 ${total} 条`"
              :page-size-options="['10', '20', '50', '100']"
              @change="handlePaginationChange"
            />
          </div>
        </div>

        <!-- 右侧：权限分配 -->
        <div class="permission-assign" v-if="selectedRole">
          <div class="assign-header">
            <h3>{{ selectedRole.roleName }} - 权限配置</h3>
            <a-button
              type="primary"
              @click="handleSavePermissions"
              :loading="saving"
            >
              保存权限
            </a-button>
          </div>

          <div class="permission-tree-wrapper">
            <a-tree
              v-model:checkedKeys="checkedPermissions"
              :tree-data="permissionTree"
              checkable
              :field-names="{
                children: 'children',
                title: 'title',
                key: 'key',
              }"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="formData" :label-col="{ span: 6 }">
        <!-- 编辑时显示角色代码（只读） -->
        <a-form-item v-if="isEdit" label="角色代码">
          <a-input v-model:value="formData.roleCode" disabled />
        </a-form-item>
        <a-form-item label="角色名称" required>
          <a-input
            v-model:value="formData.roleName"
            placeholder="请输入角色名称"
          />
        </a-form-item>
        <a-form-item label="角色描述">
          <a-textarea
            v-model:value="formData.description"
            :rows="4"
            placeholder="请输入角色描述"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch v-model:checked="formData.statusChecked" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import type { Role } from "@/types/role";
import type { PermissionTreeNode } from "@/types/permission";
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  assignPermissions,
} from "@/api/tenant/role";
import { useRouter } from "vue-router";
import { generatePermissionTree } from "@/utils/permission";
import { useUserStore } from "@/stores/user";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const saving = ref(false);
const roleList = ref<Role[]>([]);
const permissionTree = ref<PermissionTreeNode[]>([]);
const selectedRole = ref<Role | null>(null);
const checkedPermissions = ref<string[]>([]);

// 角色层级定义（数字越大权限越高）
const ROLE_HIERARCHY: Record<string, number> = {
  PLATFORM_ADMIN: 100,
  SUPER_ADMIN: 90,
  SITE_ADMIN: 80,
};

// 获取角色层级
const getRoleLevel = (roleCode: string): number => {
  return ROLE_HIERARCHY[roleCode] || 0;
};

// 判断当前用户是否可以管理目标角色
const canManageRole = (targetRoleCode: string): boolean => {
  const currentUserRole = userStore.userInfo?.role || "";
  const currentLevel = getRoleLevel(currentUserRole);
  const targetLevel = getRoleLevel(targetRoleCode);

  // 当前用户层级必须高于目标角色
  return currentLevel > targetLevel;
};

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const columns = [
  { title: "角色代码", dataIndex: "roleCode", key: "roleCode" },
  { title: "角色名称", dataIndex: "roleName", key: "roleName" },
  { title: "类型", dataIndex: "isSystem", key: "isSystem" },
  { title: "状态", dataIndex: "status", key: "status" },
  { title: "操作", key: "action", width: 250 },
];

// 弹窗相关
const modalVisible = ref(false);
const isEdit = ref(false);
const modalTitle = computed(() => (isEdit.value ? "编辑角色" : "新增角色"));
const formData = reactive({
  id: undefined as number | undefined,
  roleCode: "",
  roleName: "",
  description: "",
  statusChecked: true,
});

onMounted(() => {
  fetchRoleList();
  initPermissionTree();
});

const fetchRoleList = async () => {
  try {
    loading.value = true;
    const res = await getRoleList({
      current: pagination.current,
      size: pagination.pageSize,
    });

    const data = res.data as any;
    const allRoles = (data.records || []) as Role[];

    // 按当前登录用户角色过滤可见角色：
    // 站点管理员不应看到上级角色（如 SUPER_ADMIN / PLATFORM_ADMIN）
    const currentUserRole = userStore.userInfo?.role || "";
    const currentLevel = getRoleLevel(currentUserRole);

    roleList.value = allRoles.filter((role) => {
      const targetLevel = getRoleLevel(role.roleCode);
      // 只展示层级 <= 当前用户的角色
      return currentLevel >= targetLevel;
    });

    // 前端按过滤后的数量更新总数
    pagination.total = roleList.value.length;
  } catch (error) {
    console.error("获取角色列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const initPermissionTree = () => {
  // 从路由配置中生成权限树
  const routes = router.getRoutes();
  const mainLayoutRoute = routes.find(
    (r) => r.path === "/" && r.children && r.children.length > 0
  );

  if (mainLayoutRoute && mainLayoutRoute.children) {
    const currentUserRole = userStore.userInfo?.role || "";

    // 生成权限树，过滤掉当前用户角色无法访问的模块
    permissionTree.value = generatePermissionTree(
      mainLayoutRoute.children,
      currentUserRole
    );
    console.log("当前用户角色:", currentUserRole);
    console.log("权限树已生成:", permissionTree.value);
  } else {
    console.error("未找到主路由配置");
  }
};

const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchRoleList();
};

const handleCreate = () => {
  isEdit.value = false;
  modalVisible.value = true;
  Object.assign(formData, {
    id: undefined,
    roleCode: "",
    roleName: "",
    description: "",
    statusChecked: true,
  });
};

const handleEdit = (record: Role) => {
  isEdit.value = true;
  modalVisible.value = true;
  Object.assign(formData, {
    id: record.id,
    roleCode: record.roleCode,
    roleName: record.roleName,
    description: record.description,
    statusChecked: record.status === 1,
  });
};

const handleSubmit = async () => {
  try {
    const data: any = {
      roleName: formData.roleName,
      description: formData.description,
      status: formData.statusChecked ? 1 : 0,
    };

    // 编辑时需要传递 roleCode
    if (isEdit.value) {
      data.roleCode = formData.roleCode;
    }
    // 新增时不传 roleCode，后端会自动生成

    if (isEdit.value && formData.id) {
      await updateRole(formData.id, data);
      message.success("更新成功");
    } else {
      await createRole(data);
      message.success("创建成功");
    }

    modalVisible.value = false;
    fetchRoleList();
  } catch (error: any) {
    message.error(error.message || "操作失败");
  }
};

const handleCancel = () => {
  modalVisible.value = false;
};

const handleDelete = async (id: number) => {
  try {
    await deleteRole(id);
    message.success("删除成功");
    fetchRoleList();
  } catch (error: any) {
    message.error(error.message || "删除失败");
  }
};

const handleAssignPermissions = async (record: Role) => {
  selectedRole.value = record;
  try {
    const res = await getRolePermissions(record.id);
    checkedPermissions.value = res.data;
  } catch (error) {
    console.error("获取角色权限失败:", error);
  }
};

// 设置选中行的类名
const getRowClassName = (record: Role) => {
  return selectedRole.value?.id === record.id ? "selected-role-row" : "";
};

const handleSavePermissions = async () => {
  if (!selectedRole.value) return;

  try {
    saving.value = true;
    await assignPermissions(selectedRole.value.id, {
      permissionCodes: checkedPermissions.value,
    });
    message.success("权限保存成功");
  } catch (error: any) {
    message.error(error.message || "保存失败");
  } finally {
    saving.value = false;
  }
};

// 根据角色代码获取角色类型名称
const getRoleTypeName = (roleCode: string): string => {
  const roleTypeMap: Record<string, string> = {
    SUPER_ADMIN: "超级管理员",
    SITE_ADMIN: "站点管理员",
    PLATFORM_ADMIN: "平台管理员",
  };
  return roleTypeMap[roleCode] || "管理员";
};
</script>

<style scoped>
.role-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 固定头部区域 */
.page-header-fixed {
  flex-shrink: 0;
  background: #fff;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.action-bar {
  display: flex;
  gap: 12px;
}

/* 可滚动内容区 */
.page-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-right: 8px;
}

.content-container {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
  overflow: hidden;
}

/* 左侧角色列表 */
.role-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
  overflow: hidden;
}

.list-header {
  flex-shrink: 0;
  padding: 16px 20px 0;
  background: #fff;
  border-radius: var(--radius-lg) var(--radius-lg) 0 0;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 表格卡片 */
.table-card {
  /* flex: 1; */
  display: flex;
  flex-direction: column;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  min-height: 0;
  overflow: hidden;
}

:deep(.table-card .ant-card-body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

:deep(.ant-table-wrapper) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.ant-table) {
  border-radius: var(--radius-lg);
  flex: 1;
}

:deep(.ant-table-container) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

:deep(.ant-table-body) {
  padding-bottom: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: var(--text-primary);
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f0f9ff !important;
}

/* 选中角色的行高亮 */
:deep(.ant-table-tbody > tr.selected-role-row > td) {
  background: var(--primary-light) !important;
}

:deep(.ant-table-tbody > tr.selected-role-row:hover > td) {
  background: var(--primary-light) !important;
}

:deep(.ant-table-tbody > tr.selected-role-row > td:first-child) {
  border-left: 3px solid var(--primary-color);
  padding-left: 13px;
}

/* 分页器 */
.pagination-wrapper {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;
}

/* 右侧权限分配 */
.permission-assign {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: var(--radius-lg);
  padding: 20px;
  box-shadow: var(--shadow-sm);
  overflow: hidden;
  min-height: 0;
}

.assign-header {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.assign-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.permission-tree-wrapper {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

/* 管理员提示样式 */
.admin-tip {
  margin-top: 4px;
  font-size: 12px;
}
</style>
